package com.jrx.anytxn.param.utils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;

public class ExcelUtil {

    private static final Logger logger = LoggerFactory.getLogger(ExcelUtil.class);


    /**
     * 解析excel内容
     * @param inputStream
     * @param isXlsx
     * @param excludeHeadRow
     * @return
     */
    public static List<List<String>> analysisExcel(InputStream inputStream, boolean isXlsx, boolean excludeHeadRow) {
        List<List<String>> rows = new ArrayList<>();
        Workbook workbook;
        try {
            if (isXlsx) {
                workbook = new XSSFWorkbook(inputStream);
            } else {
                workbook = new HSSFWorkbook(inputStream);
            }
        } catch (IOException e) {
            logger.info("文件解析初始化失败: {}", e.getMessage());
            e.printStackTrace();
            return new ArrayList<>();
        }
        Consumer<Row> rowAction = row -> {
            List<String> cells = new ArrayList<>();
            row.cellIterator().forEachRemaining(cell -> {
                DataFormatter formatter = new DataFormatter();
                String value = formatter.formatCellValue(cell);
                if (StringUtils.isEmpty(value) || StringUtils.isEmpty(value.trim())){
                    return;
                }
                cells.add(value);
            });
            rows.add(cells);
        };
        Sheet sheet = workbook.getSheetAt(0);
        logger.info(sheet.getSheetName());
        Iterator<Row> rowIterator = sheet.rowIterator();
        Row row;
        if (rowIterator.hasNext()) {
            // 忽略标题行
            if (excludeHeadRow) {
                rowIterator.next();
            }
            while (rowIterator.hasNext()) {
                row = rowIterator.next();
                rowAction.accept(row);
            }
        }
        return rows;
    }

}
